import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class CanvasPage extends StatefulWidget {
  const CanvasPage({Key? key}) : super(key: key);

  @override
  _CanvasPageState createState() => _CanvasPageState();
}

class _CanvasPageState extends State<CanvasPage> {
  ui.Image? image;

  Path path = ui.Path();

  @override
  void dispose() {
    image?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    try {
      loadUiImage("assets/images/common/video_loading.png").then((img) {
        try {
          image = img;
        } catch (e) {
          // print("异常了$e");
        }
        setState(() {});
      });
    } catch (e) {
      // print("异常了$e");
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (image == null) {
      return Scaffold(
        appBar: AppBar(
          title: const Text(''),
        ),
        body: const Text("加载中..."),
      );
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text(''),
      ),
      body: Container(
        padding: const EdgeInsets.only(top: 50, left: 50),
        child: GestureDetector(
          onPanUpdate: (details) {
            path.lineTo(details.localPosition.dx, details.localPosition.dy);
            setState(() {});
            // print("0-------0");
          },
          onPanDown: (details) {
            // path.reset();
            path.moveTo(details.localPosition.dx, details.localPosition.dy);
            // setState(() {});
          },
          child: Column(
            children: [
              const Text("刮刮乐"),
              SizedBox(
                width: 208,
                height: 202,
                child: CustomPaint(
                  painter: MyPainter(image, path),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<ui.Image> loadUiImage(String imageAssetPath) async {
    final ByteData data = await rootBundle.load(imageAssetPath);
    final Completer<ui.Image> completer = Completer();
    ui.decodeImageFromList(Uint8List.view(data.buffer), (img) {
      return completer.complete(img);
    });
    return completer.future;
  }
}

class MyPainter extends CustomPainter {
  ui.Image? image;
  Path? path;
  final _paint = Paint();

  MyPainter(this.image, this.path);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawImage(image!, const Offset(0, 0), _paint);
    canvas.saveLayer(null, Paint());

    canvas.drawRect(Rect.fromLTWH(2, 6, size.width, size.height), Paint()..color = Colors.grey);

    // _paint = Paint();
    _paint.blendMode = ui.BlendMode.src;
    _paint.color = Colors.transparent;
    _paint.style = ui.PaintingStyle.stroke;
    _paint.strokeWidth = 10;
    // _paint.shader = ;
    _paint.strokeCap = ui.StrokeCap.round;
    canvas.drawPath(path!, _paint);
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}
